#!/bin/bash

echo "=========================================="
echo "  Sentinel 限流降级测试"
echo "=========================================="
echo ""

# 检查 Sentinel 控制台
echo "【步骤1】访问 Sentinel 控制台"
echo "地址：http://localhost:8858"
echo "用户名：sentinel"
echo "密码：sentinel"
echo ""
echo "提示：首次访问需要触发一次请求后才能在控制台看到应用"
echo ""
echo "按 Enter 继续..."
read

# QPS 限流测试
echo ""
echo "【步骤2】QPS 限流测试"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "1. 先发送几次请求，让 Sentinel 发现应用："
for i in {1..3}; do
  echo "  请求 $i:"
  curl -s http://localhost:8001/sentinel/qps | jq -r '.data'
  sleep 1
done

echo ""
echo "2. 现在去 Sentinel 控制台配置限流规则："
echo "   - 访问 http://localhost:8858"
echo "   - 选择 order-service 应用"
echo "   - 点击「簇点链路」"
echo "   - 找到 testQpsLimit 资源"
echo "   - 点击「+流控」按钮"
echo "   - 设置 QPS 阈值为 2"
echo "   - 点击「新增」"
echo ""
echo "配置完成后按 Enter 继续..."
read

echo ""
echo "3. 快速发送 10 个请求（间隔 0.3 秒，QPS ≈ 3）："
for i in {1..10}; do
  RESULT=$(curl -s http://localhost:8001/sentinel/qps)
  CODE=$(echo "$RESULT" | jq -r '.code')
  MSG=$(echo "$RESULT" | jq -r '.message')
  
  if [ "$CODE" == "429" ]; then
    echo "  请求 $i: ❌ 被限流 - $MSG"
  else
    echo "  请求 $i: ✅ 成功"
  fi
  sleep 0.3
done

echo ""
echo "【步骤3】热点参数限流测试"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "1. 在 Sentinel 控制台配置热点规则："
echo "   - 点击「热点规则」"
echo "   - 资源名：testHotParam"
echo "   - 限流模式：QPS 模式"
echo "   - 参数索引：0"
echo "   - 单机阈值：2"
echo "   - 统计窗口时长：1"
echo ""
echo "配置完成后按 Enter 继续..."
read

echo ""
echo "2. 测试普通用户（user1）："
for i in {1..5}; do
  RESULT=$(curl -s "http://localhost:8001/sentinel/hotparam?userId=user1")
  CODE=$(echo "$RESULT" | jq -r '.code')
  
  if [ "$CODE" == "429" ]; then
    echo "  请求 $i: ❌ 被限流"
  else
    echo "  请求 $i: ✅ 成功"
  fi
  sleep 0.3
done

echo ""
echo "【步骤4】慢调用熔断测试"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "1. 在 Sentinel 控制台配置熔断规则："
echo "   - 点击「熔断规则」"
echo "   - 资源名：testSlowCall"
echo "   - 熔断策略：慢调用比例"
echo "   - 最大 RT：500"
echo "   - 比例阈值：0.5"
echo "   - 熔断时长：10"
echo "   - 最小请求数：5"
echo ""
echo "配置完成后按 Enter 继续..."
read

echo ""
echo "2. 发送慢请求（延迟 600ms）触发熔断："
for i in {1..8}; do
  START=$(date +%s%N)
  RESULT=$(curl -s "http://localhost:8001/sentinel/slowcall?delay=600")
  END=$(date +%s%N)
  ELAPSED=$((($END - $START) / 1000000))
  
  CODE=$(echo "$RESULT" | jq -r '.code')
  
  if [ "$CODE" == "503" ]; then
    echo "  请求 $i: 🔥 服务熔断 (${ELAPSED}ms)"
  else
    echo "  请求 $i: ✅ 成功 (${ELAPSED}ms)"
  fi
  sleep 0.5
done

echo ""
echo "=========================================="
echo "  ✅ Sentinel 测试完成！"
echo "=========================================="
echo ""
echo "查看监控数据："
echo "  访问 Sentinel 控制台：http://localhost:8858"
echo "  - 实时监控：查看 QPS、RT、异常"
echo "  - 簇点链路：查看所有资源"
echo "  - 流控规则：查看和管理流控规则"
echo "  - 熔断规则：查看熔断状态"
